var tpid = ['KCYMFmJidhtFxWqgqOanxYJIKCFiMLBfBvsBj_jl9lE', 'IFTXxnpNSPkiN3H1WH4XTPlrzlDrq1ynJPNsIdUTLYs', 'ffRtOhQgIoJCgw7m4EEV1HJUO_P7OCJ-WddzYOMNWKI'];
const app = getApp();
const isTel = (value) => !/^1[3456789]\d{9}$/.test(value);
var istj = false;
import {
  $wuxDialog
} from '../../dist/index'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    current: '1', //默认显示的tabbar
    tit: ["报修记录", "我要报修", "个人中心"],
    appname: "报修平台",
    juese: 0, //角色
    jntop: 0, //胶囊按钮TOP
    jnheight: 0, //胶囊按钮高
    jnbottom: 0, //胶囊按钮bottom
    value1: '', //故障项目
    displayValue1: '请选择',
    options1: [],
    value2: '', //故障类型
    displayValue2: '请选择',
    gz1: '', //项目
    gz2: '', //故障
    gz3: '', //部门
    dwm: '', //报修人单位名
    xgdwm: '', //记录修改的单位名
    opt2: [], //记录故障类型的
    options2: [],
    gzms: "", //故障描述
    value3: '', //部门
    displayValue3: '请选择',
    options3: [{
      title: '部门',
      value: '0',
    }],
    dz: '', //报修地址
    lxr: '', //联系人
    lxrr: '', //报修人姓名
    xglxrr: '', //记录修改姓名
    value: '', //手机
    tel: '', //报修人手机
    xgtel: '', //记录修改电话
    timevalue1: [], //预约时间
    timedisplayValue1: '请选择',
    uploadurl: '', //图片上传地址
    imgs: [], //上传的图片地址
    bxlist: [], //历史记录
    dcl: 0, //待处理条目数
    wxid: 0, //如果是修改状态，要修改的ID
    animations: [
      'fadeIn',
      'fadeInDown',
      'fadeInLeft',
      'fadeInRight',
      'fadeInUp',
      'slideInUp',
      'slideInDown',
      'slideInLeft',
      'slideInRight',
      'zoom',
      'punch',
      'custom',
    ], //动画
    example: {
      animation: 'fadeIn',
      classNames: 'wux-animate--fadeIn',
      enter: true,
      exit: true,
      in: false,
    }, //动画
    options: [], //选择单位
    value9: [], //选择单位
    visibledw: false, //选择单位用的，弹出选择列
    fileList: [], //历史故障图
    lishitu: [], //历史故障图(不用了)
  },



  /**
   * 下拉选择器代码start
   * 选择项目、故障、部门
   */
  setValue(values, key) {
    let a = values.label;
    if (a.length > 10) {
      var b = a.substr(0, 10) + '...';
    } else {
      var b = a;
    }
    this.setData({
      [`value${key}`]: values.value, //值
      [`displayValue${key}`]: b, //简短（显示用的）名
      [`gz${key}`]: a //完整名
    })
  },
  onConfirm(e) {
    const {
      index
    } = e.currentTarget.dataset
    this.setValue(e.detail, index)
    console.log(`onConfirm${index}`, e.detail, "index:", index, "value:", e.detail.value);
    if (index == 1) {
      //如果维修项目变更，变更维修类型条目
      var id = e.detail.value;
      var opt2 = this.data.opt2;
      for (var i = 0; i < opt2.length; i++) {
        if (opt2[i].value == id) {
          var newopt2 = opt2[i].list;
        }
      }
      this.setData({
        options2: newopt2
      })
    }
  },
  onValueChange(e) {
    const {
      index
    } = e.currentTarget.dataset
    console.log(`onValueChange${index}`, e.detail);
    if (index == 1) {
      //如果维修项目变更，清空维修类型
      this.setData({
        options2: [],
        displayValue2: '请选择',
        value2: ''
      })
    }
  },
  onVisibleChange(e) {
    this.setData({
      visible: e.detail.visible
    })
  },
  onClick() {
    this.setData({
      visible: true
    })
  },
  /**
   * 下拉选择器end
   */




  onChange(e) { //TabBar选项卡切换
    console.log('onChange', e)
    this.setData({
      current: e.detail.key,
      'example.in': false //关闭修改资料
    })
    wx.requestSubscribeMessage({
      tmplIds: tpid
    })
    if (e.detail.key == 0) {
      this.getjilu();
    }
    if (e.detail.key == 1) {
      this.donewbaoxiu();
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var nm = wx.getStorageSync('config');
    this.setData({
      appname: nm.appname
    })
    console.log("来啦", options)
    var d = options.data;
    if (typeof (d) == 'undefined') {} else {
      var dd = JSON.parse(d);
      this.setData({
        wxid: dd.id
      })
    }

    if (this.data.current == 1) {
      this.donewbaoxiu(d);
    }
    if (this.data.current == 0) {
      this.getjilu();
    }
  },

  donewbaoxiu: function (e) {
    var that = this;
    let u = app.globalData.url + 'getbaoxiu.php';
    let d = {
      uid: wx.getStorageSync('uid')
    }
    app.http(u, d).then(res => {
      console.log(res.gzxm);

      var dw = [];
      dw.push(res.dwid);
      that.setData({
        options1: res.gzxm, //项目
        opt2: res.gzlx, //故障
        options3: res.danwei, //单位列表
        lxr: res.ming, //联系人
        value: res.tel, //手机
        value3: res.dwid, //部门
        displayValue3: res.dw, //默认单位名
        tel: res.tel,
        dwm: res.dw,
        lxrr: res.ming,
        value9: dw, //报修人单位ID
        dcl: res.dcl
      });
      if (that.data.wxid != 0) { //修改申请单 
        var data = JSON.parse(e);
        console.log("要修改的数据", data);

        var opt2 = that.data.opt2;
        for (var i = 0; i < opt2.length; i++) {
          if (opt2[i].value == data.xmid) {
            var newopt2 = opt2[i].list;
          }
        }
        var imgs = [];
        var img = data.img;
        img = img.replace(/'/g, '"');
        img = JSON.parse(img);
        var p = app.globalData.url + 'uploads/';
        for (var i = 0; i < img.length; i++) {
          //img[i] = p + img[i];
          var a = {
            uid: i,
            status: 'done',
            url: p + img[i]
          };
          imgs.push(a);
        }
        console.log("故障图", imgs)


        that.setData({
          value1: data.xmid,
          displayValue1: data.xm,
          gz1: data.xm,
          options2: newopt2,
          value2: data.gzid,
          displayValue2: data.gz,
          gz2: data.gz,
          gzms: data.ms,
          fileList: imgs,
          value3: data.bmid,
          displayValue3: data.bm,
          dz: data.dz,
          lxr: data.lxr,
          value: data.tel,
          timedisplayValue1: data.yysj,
          lishitu: img
        })
        console.log(that.data.fileList)


      }
    }).catch(res => {
      console.log('fail:', res);
    }).finally(() => {
      console.log('finally:', "结束");
    })
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    var v = [];
    var myDate = new Date(); //实例一个时间对象；
    var y = myDate.getFullYear(); //获取系统的年；
    var m = myDate.getMonth(); //获取系统月份，由于月份是从0开始计算，所以要加1
    var d = myDate.getDate(); // 获取系统日，
    var h = myDate.getHours(); //获取系统时，
    var i = myDate.getMinutes(); //分
    v.push(y, m, d, h, i);
    this.setData({ //设置预约时间
      timevalue1: v,
      timedisplayValue1: "" + y + "-" + (m + 1) + "-" + d + " " + h + ":" + i
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

    var jn = wx.getMenuButtonBoundingClientRect();
    console.log(jn)
    this.setData({
      jntop: jn.top,
      jnheight: jn.height,
      jnbottom: jn.bottom,
      uploadurl: app.globalData.url + 'upload.php',
      juese: wx.getStorageSync("zt")
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData({
      value1: '',
      displayValue1: '请选择',
      value2: '',
      displayValue2: '请选择',
      value3: '',
      displayValue3: '请选择',
      options2: [],
      lxr: this.data.lxrr,
      value: this.data.tel, //手机
      dz: '',
      gzms: "",
      fileList: []
    })
    this.onLoad();
    this.onReady();
    this.onShow();
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  onChangegzms: function (e) { //故障描述信息输入
    console.log('onChange', e);
    let b = e.detail.value;
    b = b.replace('"','“');
    b = b.replace("'","‘");
    b = b.replace(',','，');
    b = b.replace(/[\r]/g, "");
    b = b.replace(/[\n]/g, "");
    this.setData({
      gzms: b
    })
  },
  onChangedizhi: function (e) { //修改报修地址
    console.log('onChange', e);
    let b = e.detail.value;
    b = b.replace('"','“');
    b = b.replace("'","‘");
    b = b.replace(',','，');
    b = b.replace(/[\r]/g, "");
    b = b.replace(/[\n]/g, "");
    this.setData({
      dz: b
    })
  },
  onChangelxr: function (e) { //修改联系人
    console.log('onChange', e);
    let b = e.detail.value;
    b = b.replace('"','“');
    b = b.replace("'","‘");
    b = b.replace(',','，');
    b = b.replace(/[\r]/g, "");
    b = b.replace(/[\n]/g, "");
    this.setData({
      lxr: b
    })
  },

  /**
   * 选择图片并上串start
   */
  onChangeimg(e) {
    console.log('onChange', e)
    const {
      file,
      fileList
    } = e.detail
    if (file.status === 'uploading') {
      this.setData({
        progress: 0,
      })
      wx.showLoading()
    } else if (file.status === 'done') {
      console.log("上传完成", file.url)
      this.setData({
        imageUrl: file.url,
      })
    }
    console.log("完成", e.detail.fileList);
    // Controlled state should set fileList
    this.setData({
      fileList
    })
  },
  ceshitestanniu: function (e) { //测试用的
    console.log(this.data.fileList);
    var tu = this.data.fileList;
    var tupian = [];
    for (var j = 0; j < tu.length; j++) {
      if (typeof (tu[j].res) == 'undefined') { //老图
        var m = tu[j].url;
        m = m.replace(app.globalData.url + 'uploads/', '');
        tupian.push(m);
      } else { //新图
        if (tu[j].res.statusCode == 200) {
          var d = JSON.parse(tu[j].res.data);
          if (d[0].status == 1) {
            var m = d[0].file;
            tupian.push(m);
          }
        }
      }
    }
    console.log(JSON.stringify(tupian))
  },
  onSuccessimg(e) { //选择图片并上传用的
    console.log('onSuccess', e);

    if (e.detail.file.res.statusCode == 200) {
      var d = JSON.parse(e.detail.file.res.data);
      console.log('上传成功', d);
      if (d[0].status == 1) {
        var img = this.data.imgs;
        img.push(d[0].file);
        this.setData({
          imgs: img
        })
      } else {
        wx.showModal({
          content: d[0].msg + '，请删除本图片后重试。',
          showCancel: false,
          success: (res) => {
            if (res.confirm) {}
          },
        })
      }
    } else {
      wx.showModal({
        content: '上传失败，请删除本图片后重试。',
        showCancel: false,
        success: (res) => {
          if (res.confirm) {}
        },
      })
    }
  },
  onFailimg(e) { //选择图片并上传用的
    console.log('onFail', e)
  },
  onCompleteimg(e) { //选择图片并上传用的
    console.log('onComplete', e)
    wx.hideLoading()
  },
  onProgressimg(e) { //选择图片并上传用的
    console.log('onProgress', e)
    this.setData({
      progress: e.detail.file.progress,
    })
  },
  onPreviewimg(e) { //选择图片并上传用的
    console.log('onPreview', e);
    const {
      file,
      fileList
    } = e.detail
    wx.previewImage({
      current: file.url,
      urls: fileList.map((n) => n.url),
    })
  },
  onRemoveimg(e) { //选择图片并上传用的

  },
  /**
   * 选择图片并上串end
   */




  /**
   * 输入手机号start
   */
  onChangetel(e) {
    console.log('onChange', e)
    this.setData({
      error: isTel(e.detail.value),
      value: e.detail.value,
    })
  },
  onFocustel(e) {
    this.setData({
      error: isTel(e.detail.value),
    })
    console.log('onFocus', e)
  },
  onBlurtel(e) {
    this.setData({
      error: isTel(e.detail.value),
    })
    console.log('onBlur', e)
  },
  onConfirmtel(e) {
    console.log('onConfirm', e)
  },
  onCleartel(e) {
    console.log('onClear', e)
    this.setData({
      error: true,
      value: '',
    })
  },
  onErrortel() {
    wx.showModal({
      title: 'Please enter 11 digits',
      showCancel: !1,
    })
  },
  /**
   * 输入手机号end
   */


  /**
   * 选择日期start
   */
  onChangetime(e) {
    console.log(e)
    const {
      key,
      values
    } = e.detail
    const lang = values[key]
    this.setData({
      lang,
    })
  },
  setValuetime(values, key, mode) {
    this.setData({
      [`timevalue${key}`]: values.value,
      [`timedisplayValue${key}`]: values.label,
      // [`displayValue${key}`]: values.displayValue.join(' '),
    })
  },
  onConfirmtime(e) {
    const {
      index,
      mode
    } = e.currentTarget.dataset
    this.setValuetime(e.detail, index, mode)
    console.log(`onConfirm${index}`, e.detail)
  },
  onVisibleChangetime(e) {
    this.setData({
      visible1: e.detail.visible //这里visible被修改为visible1，不知行不行
    })
  },
  onClicktime() {
    this.setData({
      visible1: true //这里visible被修改为visible1，不知行不行
    })
  },
  /**
   * 选择日期end
   */
  okBTN: function (e) { //确定提交
    if (istj) {
      return;
    }
    istj = true;
    var tel = this.data.value; //手机*
    var dizhi = this.data.dz; //地址*
    var lxr = this.data.lxr; //联系人*
    var bm = this.data.value3; //部门ID*
    var bmm = this.data.displayValue3; //部门名
    var xm = this.data.value1; //维修项目*
    var xmm = this.data.gz1; //项目名
    var gz = this.data.value2; //故障类型*
    var gzm = this.data.gz2; //故障名
    var gzms = this.data.gzms; //故障描述
    var yysj = this.data.timedisplayValue1; //预约时间
    var wxid = this.data.wxid; //要修改的ID

    if (wxid == 0) {
      var img = this.data.imgs; //故障图片地址
      img = JSON.stringify(img);
    } else {
      //修改
      var tu = this.data.fileList;
      var tupian = [];
      for (var j = 0; j < tu.length; j++) {
        if (typeof (tu[j].res) == 'undefined') { //老图
          var m = tu[j].url;
          m = m.replace(app.globalData.url + 'uploads/', '');
          tupian.push(m);
        } else { //新图
          if (tu[j].res.statusCode == 200) {
            var d = JSON.parse(tu[j].res.data);
            if (d[0].status == 1) {
              var m = d[0].file;
              tupian.push(m);
            }
          }
        }
      }
      var img = JSON.stringify(tupian);
    }

    console.log("电话", tel, "地址", dizhi, "联系人", lxr, "部门名", bmm, "部门ID", bm, "项目ID", xm, "项目名", xmm, "故障ID", gz, "故障名", gzm, "描述", gzms, "预约时间", yysj, "故障图", img);
    var ok = true;
    var msg = '';
    if (isTel(tel)) {
      ok = false;
      msg = "请输入正确手机号";
    }
    if (lxr == "") {
      ok = false;
      msg = "请输入联系人";
    }
    if (dizhi == "") {
      ok = false;
      msg = "请输入地址";
    }
    if (bm == "" || bm == 0) {
      ok = false;
      msg = "请选择部门";
    }
    if (gz == "" || gz == 0) {
      ok = false;
      msg = "请选择故障类型";
    }
    if (xm == "" || xm == 0) {
      ok = false;
      msg = "请选择维修项目";
    }
    if (!ok) {
      wx.showModal({
        content: msg,
        showCancel: false,
        success: (res) => {
          if (res.confirm) {
            istj = false;
            return;
          }
        },
      })
      return false;
    }
    var u = app.globalData.url + "tibao.php";
    var uid = wx.getStorageSync('uid');
    var d = {
      uid: uid,
      tel: tel,
      dizhi: dizhi,
      lxr: lxr,
      bm: bm,
      bmm: bmm,
      xm: xm,
      xmm: xmm,
      gz: gz,
      gzm: gzm,
      yysj: yysj,
      img: img,
      gzms: gzms,
      wxid: wxid
    };
    var that = this;
    app.http(u, d).then(res => {
      wx.showModal({
        content: "提交成功",
        showCancel: false,
        success: (res) => {
          if (res.confirm) {
            istj = false;
            that.setData({
              current: 0,
              value1: '',
              displayValue1: '请选择',
              value2: '',
              displayValue2: '请选择',
              value3: '',
              displayValue3: '请选择',
              options2: [],
              lxr: that.data.lxrr,
              value: that.data.tel, //手机
              dz: '',
              gzms: "",
              fileList: []
            })
            that.getjilu();
          }
        },
      })
    }).catch(res => {
      console.log('fail:', res);
      istj = false;
    }).finally(() => {
      console.log('finally:', "结束");
    })
  },
  getjilu: function (e) { //获取我的提交记录
    wx.showLoading();
    var u = app.globalData.url + "getmylist.php";
    var uid = wx.getStorageSync('uid');
    var d = {
      uid: uid
    };
    var that = this;
    app.http(u, d).then(res => {
      var dd = res.data;
      var n = 0;
      for (var i = 0; i < dd.length; i++) {
        if (dd[i].status == 1) {
          n++;
        }
      }
      that.setData({
        bxlist: res.data,
        dcl: n
      })
    }).catch(res => {
      console.log('fail:', res);
    }).finally(() => {
      console.log('finally:', "结束");
      wx.hideLoading();
    })
  },
  changejuese: function () { //管理员切换角色
    var that = this;
    $wuxDialog().open({
      resetOnClose: true,
      title: '选择新的角色',
      verticalButtons: !0,
      buttons: [{
          text: '管理员',
          bold: !0,
          onTap(e) {
            wx.reLaunch({
              url: '/pages/guanli/guanli'
            })
          },
        },
        {
          text: '工程师',
          bold: !0,
          onTap(e) {
            wx.reLaunch({
              url: '/pages/weixiu/weixiu'
            })
          },
        },
        {
          text: '取消',
          bold: 0
        }
      ],
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    var uid = wx.getStorageSync("uid");
    var n = this.data.appname;
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target)
    }
    return {
      title: '欢迎使用' + n,
      path: '/pages/index/index',
      imageUrl: '/images/share.png',
      success: function (res) {
        // 转发成功
      },
      fail: function (res) {
        // 转发失败
      }
    }
  },
  /**
   * 动画start
   */
  onEnter(e) {
    console.log('onEnter', e.detail)
  },
  onEntering(e) {
    console.log('onEntering', e.detail)
  },
  onEntered(e) {
    console.log('onEntered', e.detail)

    // delay 300ms close animation
    setTimeout(() => this.setData({
      //'example.in': false
    }), 300)
  },
  onExit() {
    console.log('onExit')
  },
  onExiting() {
    console.log('onExiting')
  },
  onExited() {
    console.log('onExited')
  },
  onChangea(e) {
    console.log('onChange', e.detail)
  },
  /**
   * 动画end
   */

  /*
   *修改资料start
   */
  xiugaiziliao: function () { //修改资料
    //const { index } = e.currentTarget.dataset;
    //const animation = this.data.animations[index];
    const animation = 'zoom';
    //onst classNames = `wux-animate--${animation}`;
    const classNames = `wux-animate--zoom`;

    let u = app.globalData.url + 'getdanweilist.php';
    let d = {
      uid: wx.getStorageSync('uid')
    };
    var that = this;
    app.http(u, d).then(res => { //获取单位列表
      that.setData({
        'example.in': true,
        'example.classNames': classNames,
        'example.animation': animation,
        xgtel: this.data.tel,
        xgdwm: this.data.dwm,
        xglxrr: this.data.lxrr,
        options: res.data
      })
    }).catch(res => {
      console.log('fail:', res);
    }).finally(() => {
      console.log('finally:', "结束");
    })
  },
  quxiaoxgzl: function () { //取消修改资料
    this.setData({
      'example.in': false
    });
  },
  querenxgzl: function () { //确认提交修改资料
    var that = this;
    var newname = that.data.xglxrr;
    var newdwid = that.data.value9;
    var newtel = that.data.xgtel;
    var ok = true;
    var msg = '';
    if (isTel(newtel)) {
      ok = false;
      msg = "请输入正确手机号";
    }
    if (newname.length < 2) {
      ok = false;
      msg = "请输入正确姓名";
    }
    if (ok) {
      let u = app.globalData.url + "changeuserinfo.php";
      let d = {
        uid: wx.getStorageSync('uid'),
        ming: newname,
        tel: newtel,
        dw: newdwid[0]
      };
      app.http(u, d).then(res => {
        that.setData({
          lxrr: that.data.xglxrr,
          tel: that.data.xgtel,
          dwm: that.data.xgdwm,
          'example.in': false
        })
      }).catch(res => {
        console.log('fail:', res);
      }).finally(() => {
        console.log('finally:', "结束");
      })

    } else {
      wx.showModal({
        title: '提示',
        content: msg,
        showCancel: false,
        success(res) {
          if (res.confirm) {
            return false;
          }
        }
      })
    }
  },
  selectdanwei: function (e) { //弹出选择单位
    this.setData({
      visibledw: true
    })
  },
  shuruzlname: function (e) { //输入新名
    let b = e.detail.value;
    b = b.replace('"','“');
    b = b.replace("'","‘");
    b = b.replace(',','，');
    b = b.replace(/[\r]/g, "");
    b = b.replace(/[\n]/g, "");
    this.setData({
      xglxrr: b
    })
  },
  shuruzltelll: function (e) { //输入新电话
    this.setData({
      xgtel: e.detail.value
    })
  },
  /**
   * 选择新单位start
   */
  onConfirmdw(e) {
    const {
      index
    } = e.currentTarget.dataset
    this.setValuedw(e.detail, index)
    console.log(`onConfirm${index}`, e.detail)
  },
  setValuedw(values, key) {
    this.setData({
      [`value${key}`]: values.value,
      xgdwm: values.label,
    })
  },
  onVisibleChangedw(e) {
    this.setData({
      visibledw: e.detail.visible
    })
  },
  onValueChangedw(e) {
    const {
      index
    } = e.currentTarget.dataset
    console.log(`onValueChange${index}`, e.detail)
  },
  /**
   * 选择新单位end
   */

  /*
   *修改资料end
   */
  dianjikapian: function (e) {
    console.log(e)
    var idx = e.currentTarget.dataset.index; //索引
    var id = e.currentTarget.dataset.id; //工单ID
    var mod = e.currentTarget.dataset.mode;
    console.log(idx, id, mod);
    if (mod == 'bxls') {
      var dsh = this.data.bxlist;
      var data = JSON.stringify(dsh[idx]);
    }
    wx.navigateTo({
      url: '/pages/bxview/bxview?mode=' + mod + '&d=' + data + '&id=0'
    })
  },


  yinsi:function(){
    wx.navigateTo({
      url: '/pages/yinsi/yinsi',
    })
  },
})